{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(547, 730)\n",
      "(547, 730, 3)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "-1"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import cv2\n",
    "# 方法1：通过imread实现灰度处理,0灰度1彩色。直接读取灰度图片\n",
    "img0 = cv2.imread('image0.jpg',0)\n",
    "img1 = cv2.imread('image0.jpg',1)\n",
    "print(img0.shape)\n",
    "print(img1.shape)\n",
    "cv2.imshow('gray',img0)\n",
    "cv2.imshow('gbr',img1)\n",
    "cv2.waitKey(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-1"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 方法2：读取彩色图片然后处理成灰色图片 cvtColor\n",
    "img = cv2.imread('image0.jpg',1)\n",
    "# cvtColor颜色空间转换 参数1：图片 参数2：颜色转换定义宏\n",
    "dstImg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n",
    "cv2.imshow('gbrtoGray',dstImg)\n",
    "cv2.waitKey(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-1"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 源码实现灰度处理\n",
    "import numpy as np\n",
    "img = cv2.imread('image0.jpg',1)\n",
    "imgInfo = img.shape\n",
    "height = imgInfo[0]\n",
    "width = imgInfo[1]\n",
    "# BGR 算法：gray = w1*b+w2*g+w3*r w1,w2,w3代表权重\n",
    "dstImg = np.zeros((height,width,3),np.uint8)\n",
    "for i in range(0,height):\n",
    "    for j in range(0,width):\n",
    "        (b,g,r) = img[i,j]\n",
    "        # 原类型为uint8相加后可能会溢出，转换为int类型防止出现越界\n",
    "        #gray = (int(b)+int(g)+int(r))/3\n",
    "        # 心理学上的灰度计算公式 gray = r*0.299+g*0.587+b*0.114\n",
    "        b = int(b)\n",
    "        g = int(g)\n",
    "        r = int(r)\n",
    "        gray = r*0.299+g*0.587+b*0.114\n",
    "        dstImg[i,j] = np.uint8(gray)\n",
    "cv2.imshow('dstImg',dstImg)\n",
    "cv2.waitKey(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
